package com.yuntsg.nnsfcp.service.front.impl;

import cn.hutool.core.io.FileUtil;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.config.UploadConfig;
import com.yuntsg.nnsfcp.util.httpclient.SmallTool;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Calendar;

/**
 * 处理文件上传
 *
 * @author ：ljx
 * @date ：Created in 2019/5/31
 */
@Service
public class UpLoadServiceImpl {

    @Value("${upload.pathmy}")
    public String uploadPathMy;

    @Resource
    private UploadConfig uploadConfig;

    @Resource
    private HttpServletResponse response;

    @Resource
    private HttpServletRequest request;

    //  其他复杂的路径转换成标准路径
    public String OtherPathToStandPath(String path, String type) {
        // 主要是处理其他路径下的文件复制到新路径下
        String res = "";
        if (type.equals("real")) {
            if (FileUtil.exist(path)) {
                File sourceFile = new File(path);
                String[] strings = path.split("/");
                String fileName = strings[strings.length - 1];
                //todo 葛成瑞 按照这个来
                //处理文件名
                if (fileName != null) {
                    String suffix = fileName.substring(fileName.lastIndexOf("."));
                    //新的文件名 = UUID+毫秒+后缀
                    fileName = System.currentTimeMillis() + suffix;
                }
                //获取年月日,作为"文件夹"的名字
                Calendar calendar = Calendar.getInstance();
                String date = "" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);
                //服务器上使用
                String FilepathNew = uploadPathMy + (date + "/") + fileName;
                File fileCopy = new File(FilepathNew);
                FileUtil.copy(sourceFile, fileCopy, false);
                return "/upload/" + (date + "/") + fileName;
            }
        }


        return res;
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 存储后的路径
     */
    public String upLoad(MultipartFile file) throws Exception {
        if (file != null) {
            //30971520 = 30M
            int fileMaxSize = 30971520;
            if (file.getSize() > fileMaxSize) {
                CheckUtil.check(false, "文件太大");
            }

            //获取文件名
            String fileName = file.getOriginalFilename();

            //todo 葛成瑞 按照这个来
            //处理文件名
            if (fileName != null) {
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                //新的文件名 = UUID+毫秒+后缀
                fileName = System.currentTimeMillis() + suffix;
            }
            //获取年月日,作为"文件夹"的名字
            Calendar calendar = Calendar.getInstance();
            String date = "" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);

            //服务器上使用
            String path = request.getServletContext().getRealPath(uploadConfig.getUploadPath() + date + "/");

            //写入
            File newFile = new File(path, fileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);

            //判断文件是否存在
            if (newFile.exists()) {
                String[] drive = {"C:", "D:", "E:", "F:", "G:", "H:", "I:"};
                boolean contains = true;
                for (String s : drive) {
                    if (path.contains(s)) {
                        contains = false;
                    }
                }
                if (contains) {
                    //修改文件的权限 400 -r- --- ---
                    Runtime.getRuntime().exec("chmod 400 -R " + path + fileName);
                }
            }
            return uploadConfig.getUploadPath() + date + "/" + fileName;
        }
        return null;
    }

    /**
     * 下载文件
     *
     * @param filePath 文件路径(服务器上的)
     * @return
     */
    @SneakyThrows
    public void download(String filePath) throws UnsupportedEncodingException {
        // 文件名
        if (filePath != null) {
            //从下载路径中获取文件名
            String[] strings = filePath.split("/");
            String fileName = strings[strings.length - 1];

            String path = request.getServletContext().getRealPath(filePath);
            SmallTool.printMess("下载前真是路径+" + path);

            boolean exist = FileUtil.exist(path);
            if (!exist) {
                response.getWriter().write("file does not exist");
                return;
            }

            //设置文件路径
            File file = new File(path);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                // 设置强制下载不打开
                response.setContentType("application/force-download");

                //处理中问乱码
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.setCharacterEncoding("UTF-8");

                // 设置文件名
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
